package com.pricy.me;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.gson.Gson;
import com.pricy.me.adapters.CategoryAdapter;
import com.pricy.me.model.Category;
import com.pricy.me.model.CategoryIcon;
import com.pricy.me.model.User;

public class CategoryChoiceActivity extends ActionItems {
    

    private CategoryAdapter mAdapter;
    private ListView listView;
	private ProgressDialog mProgress;
	private Handler hm;
	private Handler handleError;
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, CategoryChoiceActivity.this.getString(R.string.finish))
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		return true;
	}
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	
		mProgress.setMessage(CategoryChoiceActivity.this.getString(R.string.loading));
		mProgress.show();
		
		new Thread() {
					

			@Override
			public void run() {
    	
				try {
					Gson json = new Gson();
					ArrayList<Category> userCategory = new ArrayList<Category>(); 
			    	for (int i = 0; i < mAdapter.getCount(); i++)
			        {
			    		CategoryIcon cat = mAdapter.getItem(i);
			            if (cat.isChecked())
			            {
			            	userCategory.add(new Category(cat.getId()));
			            }
			            
			        }
			    	
			    	User user = new User();
					user.loadData(getApplicationContext());
					String jsonFormat = json.toJson(userCategory);
					writeFile("usercategory.txt", jsonFormat);
					// Create a new HttpClient and Post Header
			        HttpClient httpclient = new DefaultHttpClient();
					
			        HttpPost httppost = new HttpPost(getString(R.string.lien)+"api/usercategory/?json="+URLEncoder.encode(jsonFormat, "UTF-8")+"&user="+user.getId());
					// Execute HTTP Post Request
		            HttpResponse response = httpclient.execute(httppost);
		            String reponse = EntityUtils.toString(response.getEntity());
		            Message msg = Message.obtain();
		            msg.obj = reponse;
		            hm.sendMessage(msg);
		            
				} catch (UnsupportedEncodingException e) {
					Message msg = Message.obtain();
		            msg.obj = e.toString();
					handleError.sendMessage(msg);
				} catch (ClientProtocolException e) {
					Message msg = Message.obtain();
		            msg.obj = e.toString();
					handleError.sendMessage(msg);
				} catch (IOException e) {
					Message msg = Message.obtain();
		            msg.obj = e.toString();
					handleError.sendMessage(msg);
				}
			}
		}.start();
    	
		
    	
    	return true;
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.Theme_Sherlock_Light);
        setContentView(R.layout.category_list);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        
        List<CategoryIcon> values = new ArrayList<CategoryIcon>();
        
        CategoryIcon c = new CategoryIcon(0);
        values = c.getAll(getApplicationContext());
        
        listView = (ListView) findViewById(R.id.catList);
        listView.setSelector(R.drawable.listselector);
        mAdapter = new CategoryAdapter(this, values);
        mProgress = new ProgressDialog(this);
        listView.setAdapter(mAdapter);
        
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
            	
                    CheckBox cBox = (CheckBox) view.findViewById(R.id.tv_title);
                    cBox.toggle();
                    
                    CategoryIcon cat = mAdapter.getItem(position);
                    cat.toggleChecked();

            }
        });
        
        hm = new Handler() {
            public void handleMessage(Message m) {
            	Toast.makeText(CategoryChoiceActivity.this, CategoryChoiceActivity.this.getString(R.string.yourchoicesharing), Toast.LENGTH_LONG).show();
            	mProgress.dismiss();
            	final Intent stream = new Intent(CategoryChoiceActivity.this, StreamProductsActivity.class);
            	startActivity(stream);
            }
        };
        
        handleError = new Handler() {
            public void handleMessage(Message m) {
            	Toast.makeText(CategoryChoiceActivity.this, (CharSequence) m.obj, Toast.LENGTH_LONG).show();
            	mProgress.dismiss();
            }
        };
    }
    
    
    private void writeFile(String file, String text){
		FileOutputStream fos;
		try {
			fos = getApplicationContext().openFileOutput(file, Context.MODE_PRIVATE);
			fos.write(text.getBytes());
        	fos.close();
		} catch (FileNotFoundException e) {
			Toast.makeText(getApplicationContext(), "ERROR: can't open file", Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
			Toast.makeText(getApplicationContext(), "ERROR: can't write file", Toast.LENGTH_SHORT).show();
		}	
	}

	@Override
	void actualiser() {
		// TODO Auto-generated method stub
		
	}

	@Override
	int whereami() {
		// TODO Auto-generated method stub
		return CATEGORY_CHOICE_ACTIVITY;
	}
    
   
}
